'use strict';

const BaseController = require('./base');
const serviceName = 'reservation';

class ReservationController extends BaseController {
  constructor(ctx) {
    super(ctx, serviceName);
  }

  // 创建预定
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    // 获取当前登录会员ID
    const memberId = ctx.state.member.id;
    data.memberId = memberId;
    
    const reservation = await ctx.service[this.serviceName].createReservation(data);
    ctx.success(reservation);
  }

  // 获取可预定时间段
  async getTimeSlots() {
    const { ctx } = this;
    const timeSlots = ctx.service.food.getAvailableTimeSlots();
    ctx.success(timeSlots);
  }

  // 获取我的预定列表
  async getMyReservations() {
    const { ctx } = this;
    const { status } = ctx.query;
    const memberId = ctx.state.member.id;
    
    const list = await ctx.service[this.serviceName].getMemberReservations(memberId, status);
    ctx.success(list);
  }

  // 取消预定
  async cancel() {
    const { ctx } = this;
    const id = ctx.params.id;
    const memberId = ctx.state.member.id;

    // 检查预定是否属于当前会员
    const reservation = await ctx.service[this.serviceName].findOne(id);
    if (!reservation || reservation.memberId !== memberId) {
      ctx.throw(403, '无权操作此预定');
    }

    if (reservation.status !== 1) {
      ctx.throw(400, '只能取消待确认的预定');
    }

    // 更新状态为已取消
    await ctx.service[this.serviceName].update(id, { status: 0 });
    ctx.success();
  }

  // 重写getPageQuery方法
  getPageQuery(query) {
    const where = {};
    if (query.memberId) {
      where.memberId = query.memberId;
    }
    if (query.status !== undefined) {
      where.status = query.status;
    }
    if (query.date) {
      where.reserveDate = query.date;
    }
    return where;
  }
}

module.exports = ReservationController;
